package com.shop.shoppingmall.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import com.shop.shoppingmall.config.AlipayConfig;
import com.shop.shoppingmall.dao.ShUserDao;
import com.shop.shoppingmall.dao.ShWalletDao;
import com.shop.shoppingmall.entity.ShRefundPrice;
import com.shop.shoppingmall.entity.ShUser;
import com.shop.shoppingmall.entity.ShWallet;
import com.shop.shoppingmall.service.ShDayCoinService;
import com.shop.shoppingmall.util.CommonConstant;
import com.shop.shoppingmall.util.JwtUtil;
import com.shop.shoppingmall.util.api.vo.Result;
import com.shop.shoppingmall.util.oConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransOrderQueryModel;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@RestController
@Slf4j
@CrossOrigin
@RequestMapping(value = "Alipay")
public class AilpayController  {

	@Resource
	private ShWalletDao shWalletDao;
	@Resource
	private ShUserDao shUserDao;
	@Resource
	private ShDayCoinService shDayCoinService;


	/**
	 * 单笔转账到支付宝账户
	 * https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.54Ty29&treeId=193&articleId=106236&docType=1
	 * @param content
	 * @return
	 * @throws AlipayApiException
	 */
	static	AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
			AlipayConfig.app_id,//appid
			AlipayConfig.private_key,//私钥
			"json", //格式，仅支持json
			"utf-8",//请求编码格式
			AlipayConfig.public_key,//应用公钥
			"RSA2");
	public JSONObject transfer(AlipayFundTransToaccountTransferModel model) throws AlipayApiException{
		JSONObject obj = new JSONObject();
		AlipayFundTransToaccountTransferResponse response = transferToResponse(model);
		String result = response.getBody();
		log.info("transfer result>"+result);
		log.info("@@@@@@@??>>>>   sub_msg"+response.isSuccess());
		if (response.isSuccess()) {
			JSONObject jsonObject = JSONObject.parseObject(result);
			String out_biz_no = jsonObject.getJSONObject("alipay_fund_trans_toaccount_transfer_response").getString("out_biz_no");
			log.info("提现单号"+out_biz_no);
			obj.put("aliNumber",out_biz_no);
			obj.put("Success",true);
			return obj;
		}
		obj.put("aliNumber",null);
		obj.put("Success",false);
		return obj;
	}

	public static AlipayFundTransToaccountTransferResponse transferToResponse(AlipayFundTransToaccountTransferModel model) throws AlipayApiException{
		AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
		request.setBizModel(model);
		return alipayClient.execute(request);
	}
	/**
	 * 转账查询接口
	 * @param
	 * @return
	 * @throws AlipayApiException
	 */
	public static boolean transferQuery(AlipayFundTransOrderQueryModel model) throws AlipayApiException{
		AlipayFundTransOrderQueryResponse response = transferQueryToResponse(model);
		System.out.println("transferQuery result>"+response.getBody());
		if(response.isSuccess()){
			return true;
		}
		return false;
	}
	public static AlipayFundTransOrderQueryResponse transferQueryToResponse(AlipayFundTransOrderQueryModel model) throws AlipayApiException{
		AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
		request.setBizModel(model);
		return alipayClient.execute(request);
	}
	@PostMapping("/transfer")//HttpServletRequest request ,
	public Result transfer(HttpServletRequest request ,@RequestBody ShRefundPrice shRefundPrice) {
		try {
			String nameByToken = JwtUtil.getUserNameByToken(request);
			ShUser shUser = shUserDao.selectLoginName(nameByToken);
			if(shUser == null){
				return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
			}
//			ShUser shUser = shUserDao.selectShUserByUserId("2c9ff0a87719df9e01776642f9aa0086");
			ShWallet shWallet = shWalletDao.selectWalletAll(shUser.getId());
			if(shWallet == null){
				log.info("暂时没有钱包的有关信息"+shUser.getId());
				return Result.error("暂时没有钱包的有关信息");
			}
			ShRefundPrice shRefundPrice0 = shWalletDao.selectTime();
			if(shRefundPrice0 !=null){
				log.info("今天已经提现过,不允许重复提现"+shUser.getId());
				return Result.error("今天已经提现过,不允许重复提现");
			}
			if(new BigDecimal(shRefundPrice.getAliPrice()).compareTo(new BigDecimal(10)) == 1){
				log.info("提现金额不能超过10元,用户id"+shUser.getId());
				return Result.error(CommonConstant.SC_OK_202,"每次提现金额不能超过10元");
			}
			if(shWallet.getDayCoin().compareTo(new BigDecimal(shRefundPrice.getAliPrice())) == -1){
				log.info("馨T币金额不足,用户id"+shUser.getId());
				return Result.error(CommonConstant.SC_OK_202,"专用币余额不足无法进行兑换");
			}
			//新增提现记录
			shRefundPrice.setUserId(shUser.getId());
			String salt = oConvertUtils.randomGen(16);
			shRefundPrice.setAliNumber(salt);
			shRefundPrice.setAliState("1");
			shWalletDao.insertRefund(shRefundPrice);
			if(shRefundPrice == null) {
				return Result.error("提现订单生成错误");
			}
			String total_amount = shRefundPrice.getAliPrice();
			AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
			model.setOutBizNo(shRefundPrice.getAliNumber());//生成订单号
			model.setPayeeType("ALIPAY_LOGONID");//固定值  ALIPAY_LOGON_ID  ALIPAY_LOGONID
			model.setPayeeAccount(shRefundPrice.getAliPhone());//转账收款账户
			model.setAmount(total_amount);
			model.setPayeeRealName(shRefundPrice.getAliName());
			model.setRemark("馨T网");
			JSONObject jsonObject = transfer(model);
			log.info("提现状态"+jsonObject.get("Success"));//成功 true 失败 false
			if (jsonObject.get("Success").equals(true)){
				log.info("提现成功金额为"+total_amount+"提现支付宝账号为"+shRefundPrice.getAliPhone()+"用户id为"+shUser.getId());
				//修改提现记录状态
				ShRefundPrice shRefundPrice1 = shWalletDao.selectNumber(jsonObject.get("aliNumber").toString());
				shRefundPrice1.setAliState("2");
				shWalletDao.updateRefund(shRefundPrice1);
				//修改馨T币账户余额
			    shWallet.setDayCoin(shWallet.getDayCoin().subtract(new BigDecimal(total_amount)));
			    shWalletDao.update(shWallet);
			    //添加馨T币支出记录
			    shDayCoinService.insertShCoinExpenditure(shUser.getId(),new BigDecimal(total_amount),"馨T币提现");
				return Result.ok("提现成功");
			}else{
				log.info("提现失败金额为"+total_amount+"提现支付宝账号为"+shRefundPrice.getAliPhone()+"用户id为"+shUser.getId());
				return Result.error("提现失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("异常");
		}

	}


}
